<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库" prop="depotId">
        <el-select v-model="queryParams.depotId" placeholder="请选择仓库">
          <el-option
            v-for="item in allDepot"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物品" prop="inventoryId">
        <el-select v-model="queryParams.inventoryId" placeholder="请选择物品">
          <el-option
            v-for="item in allInventory"
            :key="item.inventoryId"
            :label="item.inventFirstLetter + ' - ' + item.inventoryName"
            :value="item.inventoryId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="锁定状态" prop="lockStatus">
        <el-select v-model="queryParams.lockStatus" placeholder="请选择锁定状态" clearable>
          <el-option
            v-for="dict in dict.type.ware_lock_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['warehouse:LockRyDepotItem:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['warehouse:LockRyDepotItem:edit']"
        >修改
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['warehouse:LockRyDepotItem:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['warehouse:LockRyDepotItem:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="LockRyDepotItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="仓库" align="center" prop="depotName"/>
      <el-table-column label="商品" align="center" prop="inventoryName"/>
      <el-table-column label="锁定数量" align="center" prop="operNumber"/>
      <el-table-column label="当前库存" align="center" prop="currentNumber"/>

      <!--      <el-table-column label="仓库ID" align="center" prop="depotId" />-->
      <el-table-column label="锁定时间" align="center" prop="operTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="headerType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ware_depot_item_type" :value="scope.row.headerType"/>
        </template>
      </el-table-column>
      <el-table-column label="锁定状态" align="center" prop="lockStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ware_lock_status" :value="scope.row.lockStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['warehouse:LockRyDepotItem:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.lockStatus === '1'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['warehouse:LockRyDepotItem:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改锁定对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="仓库" prop="depotId">
          <!--          <el-input v-model="form.depotId" placeholder="请输入仓库ID" />-->
          <el-select v-model="form.depotId" placeholder="请选择仓库" :disabled="this.form.id != null?true:false">
            <el-option
              v-for="item in allDepot"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="锁定物品" prop="inventoryId">
          <!--          <el-input v-model="form.inventoryId" placeholder="请输入商品Id" />-->
          <el-select v-model="form.inventoryId" @change="onSelectedInventory" placeholder="请选择锁定物品"
                     :disabled="this.form.id != null?true:false" filterable clearable>
            <el-option
              v-for="item in allInventory"
              :key="item.inventoryId"
              :label="item.inventFirstLetter + ' - ' + item.inventoryName"
              :value="item.inventoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="this.form.id == null" label="商品规格" prop="specifications">
          <el-input v-model="form.specifications" :disabled="true"/>
        </el-form-item>
        <el-form-item v-if="this.form.id == null" label="品牌" prop="brand">
          <el-input v-model="form.brand" :disabled="true"/>
        </el-form-item>
        <el-form-item v-if="this.form.id == null" label="wbs" prop="wbs">
          <el-input v-model="form.wbs" :disabled="true"/>
        </el-form-item>
        <el-form-item v-if="this.form.id == null" label="总库数量" prop="currentNumber">
          <el-input v-model="form.currentNumber" :disabled="true"/>
        </el-form-item>
        <el-form-item v-if="this.form.id == null" label="已锁定数量" prop="lockNumber">
          <el-input v-model="lockNumber" :disabled="true"/>
        </el-form-item>

        <el-form-item v-if="this.form.id == null" label="当前可用数量" prop="surPlusNum">
          <el-input v-model="surPlusNum" :disabled="true"/>
        </el-form-item>
        <el-form-item label="锁定数量" prop="operNumber">
          <el-input v-model.number="form.operNumber" placeholder="请输入锁定数量" @blur="compareTwo"
                    :disabled="this.form.id != null?true:false"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="锁定状态">
          <el-radio-group v-model="form.lockStatus">
            <el-radio
              v-for="dict in dict.type.ware_lock_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLockRyDepotItem,
  getLockRyDepotItem,
  delLockRyDepotItem,
  addLockRyDepotItem,
  updateLockRyDepotItem
} from "@/api/warehouse/LockRyDepotItem";
import {allRyInventory, getRyInventory} from "@/api/inventory/RyInventory";
import {allRyDepot} from "@/api/warehouse/RyDepot";
import {getInfoByDepotInventoryId, getInventoryByDepotId} from "@/api/warehouse/WareCurrentStock";
import {getLockNumById} from "@/api/warehouse/RyDepotItem";

export default {
  name: "LockRyDepotItem",
  dicts: ['ware_depot_item_type', 'ware_lock_status'],
  data() {
    return {
      //所有仓库
      allDepot: [{
        id: 1,
        name: '总仓库'
      }],
      //所有物品
      allInventory: [],
      lockNumber: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      surPlusNum: null,
      // 总条数
      total: 0,
      // 锁定表格数据
      LockRyDepotItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inventoryId: null,
        depotId: null,
        lockStatus: null,
      },
      //仓库中物品信息查询参数
      params: {
        depotId: null,
        inventoryId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        depotId: [
          {required: true, message: "仓库不能为空", trigger: "blur"}
        ],
        inventoryId: [
          {required: true, message: "商品不能为空", trigger: "blur"}
        ],
        operNumber: [
          {required: true, message: "锁定数量不能为空", trigger: "blur"},
          {type: "number", message: "锁定数量只能为数字类型", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.allRyInventory();
  },
  methods: {
    //根据仓库id和物品id查询仓库中此物品基本信息和当前数量
    onSelectedInventory(val) {//这里的val是物品id
      if (val === '') {// val为空 是输入框清空  重置表单
        this.reset()
        this.surPlusNum = ''
      } else {

        console.log("params: " + val + " | " + this.form.depotId);
        this.params.depotId = this.form.depotId;
        this.params.inventoryId = val;

        getInfoByDepotInventoryId(this.params).then(response => {

          let resultData = {
            depotId: this.form.depotId,
            inventoryId: this.form.inventoryId,
            specifications: response.data.specifications,
            brand: response.data.brand,
            wbs: response.data.wbs,
            currentNumber: response.data.currentNumber,
            lockStatus: "0",
            lockNumber: null,
            operNumber: null,
          };
          this.form = resultData;
          //查询已锁定数量
          getLockNumById(this.params).then(response => {
            //已锁定数量清空
            this.lockNumber = 0;
            if (typeof (response.data) != "undefined") {
              console.log("--->" + response.data);
              this.lockNumber = response.data.operNumber;
              this.form.lockNumber = this.lockNumber;
              console.log("locaNum:" + this.form.lockNumber);
            } else {
              this.form.lockNumber = 0;
              console.log(this.form.lockNumber);
            }
            this.surPlusNum = eval(this.form.currentNumber) - eval(this.form.lockNumber);
          });
        });
      }
    },

    //根据仓库id查询仓库中物品列表
    allRyInventory() {
      let depotId = 1;//总库id为1
      getInventoryByDepotId(depotId).then(response => {
        this.allInventory = response.data;
      });
    },

    /** 查询锁定列表 */
    getList() {
      this.loading = true;
      listLockRyDepotItem(this.queryParams).then(response => {
        this.LockRyDepotItemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    //比较当前数量和锁定数量
    compareTwo() {
      if (this.form.operNumber) {
        if (this.form.lockNumber) {//判断是否存在已锁定数量
          console.log("锁定数量存在！");
          let num = this.form.currentNumber - this.form.lockNumber;
          if (this.form.operNumber > num) {
            this.$message({
              message: '警告，锁定数量不能大于仓库物品当前可用数量！',
              type: 'warning'
            });
            this.form.operNumber = null;
          }
        } else {
          console.log("锁定数量不存在！");
          if (this.form.operNumber > this.form.currentNumber) {
            this.$message({
              message: '警告，锁定数量不能大于仓库物品当前可用数量！',
              type: 'warning'
            });
            this.form.operNumber = null;
          }
        }
      } else {
        this.$message({
          message: '警告，锁定数量不能小于一个！',
          type: 'warning'
        });
        this.form.operNumber = null;
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.surPlusNum = ''
    },
    // 表单重置
    reset() {
      this.lockNumber = null,
        this.form = {
          id: null,
          headerId: null,
          inventoryId: null,
          operNumber: null,
          lockNumber: null,
          specifications: null,
          brand: null,
          wbs: null,
          currentNumber: null,
          remark: null,
          depotId: 1,
          anotherDepotId: null,
          headerType: null,
          lockStatus: "0",
          taxRate: null,
          taxMoney: null,
          taxLastMoney: null,
          snList: null,
          batchNumber: null,
          expirationDate: null,
          linkId: null,
          tenantId: null,
          delFlag: null,
          surPlusNum: null,
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.surPlusNum = '';
      this.open = true;
      this.title = "添加锁定";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLockRyDepotItem(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改锁定";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLockRyDepotItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.operNumber <= 0){
              this.$modal.msgWarning('锁定数量不能为0或负数')
            }else{
              addLockRyDepotItem(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }

          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除锁定编号为"' + ids + '"的数据项？').then(function () {
        return delLockRyDepotItem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehouse/LockRyDepotItem/export', {
        ...this.queryParams
      }, `LockRyDepotItem_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
